package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 451. 根据字符出现频率排序
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/8 17:45
 */
public class FrequencySort {

    public static void main(String[] args) {
        FrequencySort test = new FrequencySort();
        String leetcode = test.frequencySort("leetcodeo");
        System.out.println(leetcode);
    }

    public String frequencySort(String s) {
        int[][] arr = new int[128][2];
        int i = 0;
        for (int[] ints : arr) {
            ints[0] = i++;
        }
        for (char aChar : s.toCharArray()) {
            arr[aChar][1]++;
        }
        Arrays.sort(arr, (a, b) -> b[1] - a[1]);
        StringBuilder sb = new StringBuilder(s.length());
        for (int[] ints : arr) {
            int count = ints[1];
            if (count == 0) {
                break;
            }
            char c = (char) ints[0];
            for ( i = 0; i < count; i++) {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
